<template>
<div>
    <a-spin :spinning="state.loading">
        <div>
            选择图片上传
        </div>
        <a-upload-dragger
                name="file"
                :multiple="false"
                :file-list="state.fileList"
                :before-upload="beforeUpload"
                @remove="handleRemove"
        >
            <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">点击获取拖拽选择文件上传</p>
        </a-upload-dragger>
        <div style="margin-top: 20px;">
            <a-button type="primary" @click="handleUpload">
                上传
            </a-button>
        </div>


        <div style="margin:10px 0" v-if="state.src">
            <p>上传成功的图片：</p>
            <a-image :src="state.src"></a-image>
        </div>
    </a-spin>
</div>
</template>
<script lang="ts" setup>
    import { reactive } from 'vue';
    import { InboxOutlined } from '@ant-design/icons-vue';
    import { message } from 'ant-design-vue';
    import {uploadImgFile} from '@/service/upload/index'
    import {globalEnv} from '@/utils/index.ts'
    const state:any=reactive({
        loading:false,
        fileList:[],
        src:''
    })
    const beforeUpload=(file:File)=>{
        state.fileList=[file]
        return false;
    }

    const handleRemove = (file) => {
        state.fileList=[]
    };

    const handleUpload = async () => {
        if(!state.fileList.length){
            return message.warn('请选择文件')
        }
        const formData = new FormData();
        state.fileList.forEach((file: any) => {
            formData.append('file', file as any);
        });
        state.loading = true;
        try{
            const res=await uploadImgFile(formData)
            console.log('res',res)
            const id=res.data.data.id
            const env=globalEnv()
            state.src=env.VITE_APP_HOST+`/api/media/render?id=${id}`
            console.log('state.src',state.src)
            message.success('上传成功！')
        }
        catch (e) {
            message.error(JSON.stringify(e))
        }
        state.loading = false;
    };

</script>
